<template>
  <div class="app-container">
    <!-- 资产概览 -->
    <div class="asset-overview">
      <div class="main-card">
        <div class="total-assets">
          <div class="title">总资产 (USDT)</div>
          <div class="amount">{{ totalAssets }}</div>
          <div class="change" :class="assetChange >= 0 ? 'positive' : 'negative'">
            <i :class="assetChange >= 0 ? 'el-icon-caret-top' : 'el-icon-caret-bottom'"></i>
            {{ assetChange >= 0 ? '+' : '' }}{{ assetChange }}%
          </div>
        </div>
        <div class="balance-info">
          <div class="balance-item">
            <div class="label">可用余额</div>
            <div class="value">{{ availableBalance }} USDT</div>
          </div>
          <div class="balance-item">
            <div class="label">冻结金额</div>
            <div class="value">{{ frozenAmount }} USDT</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 资产分布和资金记录 -->
    <div class="asset-details">
      <el-card class="distribution-card">
        <div slot="header" class="card-header">
          <span class="title">资产分布</span>
          <el-button-group>
            <el-button size="small" :type="displayMode === 'list' ? 'primary' : ''" @click="displayMode = 'list'">
              <i class="el-icon-tickets"></i>
            </el-button>
            <el-button size="small" :type="displayMode === 'chart' ? 'primary' : ''" @click="displayMode = 'chart'">
              <i class="el-icon-pie-chart"></i>
            </el-button>
          </el-button-group>
        </div>
        <div v-if="displayMode === 'list'" class="asset-list">
          <div v-for="(asset, index) in assetDistribution" :key="index" class="asset-item">
            <div class="asset-info">
              <div class="symbol">{{ asset.symbol }}</div>
              <div class="amount">{{ asset.amount }}</div>
            </div>
            <div class="asset-value">
              <div class="value">≈ {{ asset.value }} USDT</div>
              <div class="percentage">{{ asset.percentage }}%</div>
            </div>
          </div>
        </div>
        <div v-else class="chart-container" ref="distributionChart"></div>
      </el-card>

      <el-card class="records-card">
        <div slot="header" class="card-header">
          <span class="title">资金记录</span>
          <div class="header-right">
            <el-select v-model="recordType" size="small" style="width: 120px">
              <el-option label="全部" value="all"></el-option>
              <el-option label="充值" value="deposit"></el-option>
              <el-option label="提现" value="withdraw"></el-option>
            </el-select>
          </div>
        </div>
        <el-table :data="fundRecords" style="width: 100%">
          <el-table-column prop="time" label="时间" width="180"></el-table-column>
          <el-table-column prop="type" label="类型" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.type === 'deposit' ? 'success' : 'warning'" size="mini">
                {{ scope.row.type === 'deposit' ? '充值' : '提现' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="金额">
            <template slot-scope="scope">
              <span :class="scope.row.type === 'deposit' ? 'positive' : 'negative'">
                {{ scope.row.type === 'deposit' ? '+' : '-' }}{{ scope.row.amount }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === 'success' ? 'success' : 'danger'" size="mini">
                {{ scope.row.status === 'success' ? '成功' : '失败' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 资产趋势 -->
    <el-card class="trend-card">
      <div slot="header" class="card-header">
        <span class="title">资产趋势</span>
        <div class="header-right">
          <el-radio-group v-model="timeRange" size="small" @change="updateTrendChart">
            <el-radio-button label="week">近一周</el-radio-button>
            <el-radio-button label="month">近一月</el-radio-button>
            <el-radio-button label="year">近一年</el-radio-button>
          </el-radio-group>
        </div>
      </div>
      <div class="chart-container" ref="trendChart"></div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'AssetOverview',
  data() {
    return {
      totalAssets: '52,189.00',
      assetChange: 13.5,
      availableBalance: '35,420.50',
      frozenAmount: '16,768.50',
      displayMode: 'list',
      recordType: 'all',
      timeRange: 'week',
      assetDistribution: [
        {
          symbol: 'USDT',
          amount: '35,420.50',
          value: '35,420.50',
          percentage: 67.87
        },
        {
          symbol: 'BTC',
          amount: '0.25',
          value: '8,855.13',
          percentage: 16.97
        },
        {
          symbol: 'ETH',
          amount: '3.65',
          value: '7,913.37',
          percentage: 15.16
        }
      ],
      fundRecords: [
        {
          time: '2025-05-26 15:30:00',
          type: 'deposit',
          amount: '10,000.00 USDT',
          status: 'success'
        },
        {
          time: '2025-05-26 14:20:00',
          type: 'withdraw',
          amount: '5,000.00 USDT',
          status: 'success'
        },
        {
          time: '2025-05-26 13:15:00',
          type: 'deposit',
          amount: '20,000.00 USDT',
          status: 'success'
        }
      ],
      charts: {
        distribution: null,
        trend: null
      }
    }
  },
  watch: {
    displayMode: {
      handler(newVal) {
        this.$nextTick(() => {
          if (newVal === 'chart') {
            this.initDistributionChart()
          } else {
            // 如果有图表实例，在切换到列表模式时销毁它
            if (this.charts.distribution) {
              this.charts.distribution.dispose()
              this.charts.distribution = null
            }
          }
        })
      },
      immediate: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts()
      window.addEventListener('resize', this.resizeCharts)
    })
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts)
    Object.values(this.charts).forEach(chart => {
      if (chart) {
        chart.dispose()
      }
    })
  },
  methods: {
    initCharts() {
      this.initDistributionChart()
      this.initTrendChart()
    },
    initDistributionChart() {
      if (this.displayMode === 'chart' && this.$refs.distributionChart) {
        if (this.charts.distribution) {
          this.charts.distribution.dispose()
        }
        this.charts.distribution = echarts.init(this.$refs.distributionChart)
        this.charts.distribution.setOption({
          tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} USDT ({d}%)'
          },
          legend: {
            orient: 'vertical',
            right: '5%',
            top: 'center',
            itemWidth: 10,
            itemHeight: 10,
            itemGap: 20,
            formatter: name => {
              const item = this.assetDistribution.find(asset => asset.symbol === name)
              return `${name}  ${item.percentage}%`
            }
          },
          series: [
            {
              name: '资产分布',
              type: 'pie',
              radius: ['40%', '70%'],
              center: ['40%', '50%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '20',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: this.assetDistribution.map(asset => ({
                name: asset.symbol,
                value: parseFloat(asset.value.replace(',', '')),
                itemStyle: {
                  color: this.getAssetColor(asset.symbol)
                }
              }))
            }
          ]
        })
      }
    },
    initTrendChart() {
      if (this.$refs.trendChart) {
        if (this.charts.trend) {
          this.charts.trend.dispose()
        }
        this.charts.trend = echarts.init(this.$refs.trendChart)
        this.updateTrendChart()
      }
    },
    updateTrendChart() {
      if (!this.charts.trend) return

      // 生成趋势数据
      const trendData = this.generateTrendData()

      this.charts.trend.setOption({
        tooltip: {
          trigger: 'axis',
          formatter: params => {
            const data = params[0]
            return `${data.name}<br/>${data.value} USDT`
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: trendData.dates,
          axisLine: {
            lineStyle: {
              color: '#DCDFE6'
            }
          },
          axisLabel: {
            color: '#606266'
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            show: false
          },
          axisLabel: {
            color: '#606266',
            formatter: value => `${value} USDT`
          },
          splitLine: {
            lineStyle: {
              color: '#EBEEF5'
            }
          }
        },
        series: [
          {
            name: '总资产',
            type: 'line',
            smooth: true,
            showSymbol: false,
            data: trendData.values,
            lineStyle: {
              color: '#409EFF',
              width: 3
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgba(64,158,255,0.2)'
                },
                {
                  offset: 1,
                  color: 'rgba(64,158,255,0)'
                }
              ])
            }
          }
        ]
      })
    },
    resizeCharts() {
      Object.values(this.charts).forEach(chart => {
        if (chart) {
          chart.resize()
        }
      })
    },
    getAssetColor(symbol) {
      const colorMap = {
        'USDT': '#26A17B',
        'BTC': '#F7931A',
        'ETH': '#627EEA'
      }
      return colorMap[symbol] || '#409EFF'
    },
    generateTrendData() {
      const now = new Date()
      const dates = []
      const values = []
      const baseValue = 50000
      let count

      switch (this.timeRange) {
        case 'week':
          count = 7
          break
        case 'month':
          count = 30
          break
        case 'year':
          count = 12
          break
      }

      for (let i = count - 1; i >= 0; i--) {
        const date = new Date()
        if (this.timeRange === 'year') {
          date.setMonth(now.getMonth() - i)
          dates.push(date.toLocaleDateString('zh-CN', { month: 'short' }))
        } else {
          date.setDate(now.getDate() - i)
          dates.push(date.toLocaleDateString('zh-CN', { month: 'numeric', day: 'numeric' }))
        }
        
        // 生成模拟数据
        const randomFactor = 1 + (Math.random() * 0.4 - 0.2)
        values.push((baseValue * randomFactor).toFixed(2))
      }

      return { dates, values }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .asset-overview {
    margin-bottom: 20px;

    .main-card {
      background-color: white;
      border-radius: 6px;
      padding: 30px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
      display: flex;
      justify-content: space-between;
      align-items: flex-start;

      .total-assets {
        .title {
          color: #7f8c8d;
          font-size: 14px;
          margin-bottom: 10px;
        }

        .amount {
          font-size: 32px;
          font-weight: 600;
          margin-bottom: 10px;
        }

        .change {
          display: flex;
          align-items: center;
          font-size: 14px;

          i {
            margin-right: 4px;
          }
        }
      }

      .balance-info {
        display: flex;
        gap: 40px;

        .balance-item {
          text-align: center;

          .label {
            color: #7f8c8d;
            font-size: 14px;
            margin-bottom: 10px;
          }

          .value {
            font-size: 20px;
            font-weight: 600;
          }
        }
      }
    }
  }

  .asset-details {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
    margin-bottom: 20px;

    .distribution-card {
      .chart-container {
        height: 300px;
      }
    }
  }

  .trend-card {
    margin-bottom: 20px;

    .chart-container {
      height: 400px;
    }
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 16px;
      font-weight: 600;
    }
  }

  .asset-list {
    .asset-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px 0;
      border-bottom: 1px solid #EBEEF5;

      &:last-child {
        border-bottom: none;
      }

      .asset-info {
        .symbol {
          font-weight: 600;
          margin-bottom: 5px;
        }

        .amount {
          color: #606266;
          font-size: 14px;
        }
      }

      .asset-value {
        text-align: right;

        .value {
          font-weight: 500;
          margin-bottom: 5px;
        }

        .percentage {
          color: #909399;
          font-size: 12px;
        }
      }
    }
  }

  .positive {
    color: #67C23A;
  }

  .negative {
    color: #F56C6C;
  }
}
</style> 